﻿using System;
using System.Collections.Generic;
using NHibernate;

namespace Repetition.Persistence.NHibernate
{
    public class PersistentContext : IDisposable, IPersistentContext
    {
        private ISession session;

        public PersistentContext()
        {
            session = SessionFactorySingleton.OpenSession();
        }

        ~PersistentContext()
        {
            Dispose();
        }

        public void Save<T>(T obj) where T : IPersistable
        {
            using(var repository = new Repository<T>(session))
            {
                if (IsPersisted(obj))
                    repository.Update(obj);
                else
                    repository.Add(obj);
            }
        }

        public ICollection<T> GetAll<T>() where T : IPersistable
        {
            using (var repository = new Repository<T>(session))
            {
                return repository.GetAll();
            }
        }

        public void Remove<T>(T obj) where T : IPersistable
        {
            if (IsPersisted(obj))
            {
                using (var repository = new Repository<T>(session))
                {
                    repository.Remove(obj);
                }
            }
        }

        public bool IsPersisted(IPersistable obj)
        {
            return obj.Id > 0;
        }

        public void Dispose()
        {
            //session.Dispose();
        }
    }
}
